package com.itmsoft.util;

import com.itmsoft.test.utils.MockContainer;

import org.apache.catalina.LifecycleState;
import org.apache.catalina.core.AprLifecycleListener;
import org.apache.catalina.core.StandardServer;
import org.apache.catalina.startup.Tomcat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WebContainer
{
    private Logger log = LoggerFactory.getLogger(WebContainer.class);

    @SuppressWarnings("unused")
    private MockContainer c = new MockContainer(this, "../services/");
    private static final int PORT = 1234;
    private static final String CONTEXT_ROOT = "/" + Constants.TRAINEE_SURNAME + "-ejb-app";
    public static final String URL = "http://localhost:" + PORT + CONTEXT_ROOT;
    private static Tomcat tomcat;

    public WebContainer() throws Exception
    {
        log.debug("Starting web server.");
        try
        {
            if (tomcat != null && LifecycleState.STARTED.equals(tomcat.getServer().getState()))
            {
                log.debug("Server already running. Returning.");
                return;
            }
            tomcat = new Tomcat();
            tomcat.setPort(PORT);
            tomcat.setBaseDir("target" + Constants.FILE_SEPARATOR);
            tomcat.getHost().setAppBase(
                ".." + Constants.FILE_SEPARATOR + "src" + Constants.FILE_SEPARATOR + "main"
                    + Constants.FILE_SEPARATOR);

            // Add AprLifecycleListener
            StandardServer server = (StandardServer) tomcat.getServer();
            server.addLifecycleListener(new AprLifecycleListener());

            tomcat.addWebapp(CONTEXT_ROOT, "webapp");
            tomcat.start();

            log.info("Web container started. Url: {}", URL);
        }
        catch (Exception e)
        {
            log.error("Web container start failed.", e);
            throw new RuntimeException("Failed to start web container.", e);
        }
    }

    public void join() throws InterruptedException
    {
        tomcat.getServer().await();
    }

}
